// const { baseUrl } = require('./config')
const api = require('./api');

let openid = ''

// 格式化时间
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

// 选择图片
const chooseMedia = (options, callback) => {
  wx.chooseMedia({
      count: 1,
      mediaType: ['image'], // ['image', 'video'] // 文件类型
      sizeType: ['original', 'compressed'], // 仅对 mediaType 为 image 时有效，是否压缩所选文件
      sourceType: ['album', 'camera'], // 图片和视频选择的来源
      maxDuration: 60, // 拍摄视频最长拍摄时间，单位秒
      ...options,
      success (res) {
        const tempFiles = res.tempFiles || []
        console.log('------res------', res)
        tempFiles.forEach(item => {
            console.log('image', item)
            callback(item)
        })
      },
      fail (err) {
          console.log('err---------------', err)
      }
  })
}

// 选择图片
const chooseImage = (callback, options) => {
  return chooseMedia({
    mediaType: ['image'],
    ...options
  }, (res) => {
    uploadFile(res.tempFilePath, callback)
  })
}

// 选择视频
const chooseVideo = (callback) => {
  return chooseMedia({
    mediaType: ['video']
  }, (res) => {
    uploadFile(res.tempFilePath, callback)
  })
}

// 上传
const uploadFile = (path, callback) => {
    if(!openid){
      openid = wx.getStorageSync('openid')
    }
    wx.uploadFile({
      url: api.upload, 
      filePath: path,
      name: 'multipartFile',
      // formData: { user: 'test' },
      header: {
        openid
      },
      success (res){
        const data = JSON.parse(res.data)
        console.log('uploadFile', data)
        console.log('uploadFile', typeof data)
        // callback(data)
        //do something
        if(data.code === '200'){
          callback(data.data.fileUrl)
          // onsole.log('uploadFile', data.data.fileUrl)
        }
      }
    })
}

// 弹框提示
const toast = (title) => {
  wx.showToast({
    icon: 'none',
    title,
  })
}

module.exports = {
  formatTime,
  chooseImage,
  chooseVideo,
  uploadFile,
  toast
}
